package objectdiagrameditor.features.link;

import org.eclipse.graphiti.features.ICreateConnectionFeature;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.context.ICreateConnectionContext;
import org.eclipse.graphiti.features.context.impl.AddConnectionContext;
import org.eclipse.graphiti.features.impl.AbstractCreateConnectionFeature;
import org.eclipse.graphiti.mm.pictograms.Connection;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;

import fUML.Semantics.Classes.Kernel.KernelFactory;
import fUML.Semantics.Classes.Kernel.Link;

public class CreateLinkConnectionFeature extends AbstractCreateConnectionFeature
		implements ICreateConnectionFeature {

	public CreateLinkConnectionFeature(IFeatureProvider fp) {
		super(fp, "Link", "Creates a new Link between two Objects");
	}

	@Override
	public boolean canStartConnection(ICreateConnectionContext context) {
		return getBusinessObjectForPictogramElement(context.getSourcePictogramElement()) instanceof fUML.Semantics.Classes.Kernel.Object;
	}

	@Override
	public boolean canCreate(ICreateConnectionContext context) {
		PictogramElement sourcePictogramElement = context.getSourcePictogramElement();
		PictogramElement targetPictogramElement = context.getTargetPictogramElement();

		// TODO: check for right domain object instance below
		 if (getBusinessObjectForPictogramElement(sourcePictogramElement) instanceof fUML.Semantics.Classes.Kernel.Object
				 && getBusinessObjectForPictogramElement(targetPictogramElement) instanceof fUML.Semantics.Classes.Kernel.Object) {
		  	return true;
		 }
		
		return sourcePictogramElement != null && targetPictogramElement != null;
	}

	@Override
	public Connection create(ICreateConnectionContext context) {
		Connection newConnection = null;

		// TODO: create the domain object connection here
		Link newLinkConnetion = (fUML.Semantics.Classes.Kernel.Link) KernelFactory.eINSTANCE.createLink();
		AddConnectionContext addContext = new AddConnectionContext(context.getSourceAnchor(), context.getTargetAnchor());
		addContext.setNewObject(newLinkConnetion);
		newConnection = (Connection) getFeatureProvider().addIfPossible(addContext);

		return newConnection;
	}
}
